package com.jxx.config;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jxx.mapper.AdminMapper;
import com.jxx.pojo.Admin;
import com.jxx.util.AdminThreadLocal;
import org.apache.shiro.authc.*;
import org.apache.shiro.authc.credential.CredentialsMatcher;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * @author Zcc
 * @desc 使用shiro框架实现登录拦截
 * @date 2020年11月18日23:49:32
 */
public class AdminRealm extends AuthorizingRealm {
    @Autowired
    private AdminMapper adminMapper;

    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        return null;
    }
    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        UsernamePasswordToken userToken = (UsernamePasswordToken) authenticationToken;
        //连接真实数据库
        QueryWrapper<Admin> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("admin_account", userToken.getUsername());
        Admin admin = adminMapper.selectOne(queryWrapper);

        if (admin==null){//没有这个人
            return null; //UnknownAccountException
        }
        AdminThreadLocal.set(admin);
        ByteSource salt = ByteSource.Util.bytes(admin.getSalt());
        return new SimpleAuthenticationInfo(admin,
                                            admin.getAdminPassword(),
                                            salt,
                                            getName());
    }
    @Override
    public CredentialsMatcher getCredentialsMatcher() {
        HashedCredentialsMatcher credentialsMatcher=new HashedCredentialsMatcher();
        credentialsMatcher.setHashAlgorithmName("MD5");
        credentialsMatcher.setHashIterations(10);
        return credentialsMatcher;
    }

}

